<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport"
        content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0" />
    <meta name="format-detection" content="telephone=no,email=no,date=no,address=no">
    <link rel="stylesheet" type="text/css" href="../css/aui.2.0.css" />
    <link rel="stylesheet" type="text/css" href="../css/aui-flex.css" />
    <style>
    </style>
</head>
<style>
    .home:before {
        content: url(../image/home.png);
    }

    .refresh:before {
        content: url(../image/refresh.png);
    }

    .company:before {
        content: url(../image/company.png);
    }

    .pa-title {
        font-size: 17px;
        color: black;
        font-weight: bold;
    }

    .pa-title-content {
        font-size: 17px;
        color: black;
    }

    body {
        background-color: #D9D8DB;
    }

    .pa_smbf_t {
        background-color: #254060;
        height: 300px;
        color: white;
        overflow: auto;
    }

    .pa_smbf_but {
        height: 58px;
        line-height: 58px;
        float: right;
        width: 120px;
        font-size: 25px;
        color: white;
        margin-right: 20px;
        text-align: center;
    }

    p {
        font-size: 17px;
        color: black;
        font-weight: bold;
        text-align: center;
    }

    table {
        width: 100%;
        table-layout: fixed;
        word-wrap: break-word;
    }

    td {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
    }

    .pa_work_order {
        background-color: #254060;
        height: 80px;
        color: white;
    }

    .line_class {
        background-color: #254060;
        height: 70px;
        color: white;
    }

    .startBut {
        height: 50px;
        line-height: 50px;
        margin-top: 30px;
        margin-left: 12px;
        float: left;
        width: 80px;
        font-size: 18px;
        color: white;
        text-align: center;

    }

    .pa_kbddProd_inner {
        background-color: #D9D8DB;
        border: 0;
        float: left;
        margin-left: 10px;
    }

    .pa_kbddProd {
        font-size: 15px;
        float: left;
        height: 56px;
        line-height: 56px;
        text-align: center;
        margin-left: 5px;
    }

    .pa_kbddProd_con {
        background-color: white;
        float: left;
        width: 100px;
        margin-top: 13px;
    }

    .marquee {
        white-space: nowrap;
        animation: marquee 5s linear infinite;
    }

    @keyframes marquee {
        0% {
            transform: translateX(100%);
        }

        100% {
            transform: translateX(-150%);
        }
    }
</style>

<body>
    <header class="aui-bar aui-bar-nav" style="background-color: #D9D8DB">
        <div style="width: 10%;height: 60px;float: left;padding-top: 6px;">
            <a class="aui-pull-left aui-btn ">
                <span class="aui-iconfont company"></span>
            </a>
        </div>
        <div style="width: 10%;height: 60px;float: left;">
            <div style="text-align: left;">
                <span class="pa-title">富晟久泰</span>
            </div>
        </div>
        <div style="width: 70%;height: 60px;float: left;">
            <div style="width:20%; float: left; text-align: left;">
                <span class="pa-title-content" id="locationName"></span>
            </div>
            <div style="width:25%; float: left; text-align: left;">
                <span class="pa-title-content" id="workCenterName"></span>
            </div>
            <div style="width:15%; float: left; text-align: left;">
                <span class="pa-title-content" id="workCellName"></span>
            </div>
            <div style="width:40%; float: left; text-align: left;">
                <span class="pa-title-content" id="nowDate"></span>
            </div>
        </div>
        <div style="width: 5%;height: 50px;float: left;">
            <a class="aui-pull-right aui-btn " onclick="refresh()">
                <span class="aui-iconfont refresh"></span>
            </a>
        </div>
        <div style="width: 5%;height: 50px;float: left;">
            <a class="aui-pull-right aui-btn" onclick="closeWin()">
                <span class="aui-iconfont home"></span>
            </a>
        </div>
    </header>
    <div class="aui-content">
        <div class="aui-flex-col aui-flex-center" style="height: 15px;">
            <div class="aui-flex-item-12">
                <p>生产排料</p>
            </div>
        </div>

    </div>

    <div class="aui-flex-col aui-flex-center" style="margin-top: 1%;">
        <div class="aui-flex-item-12">
            <div class="aui-flex-col pa_work_order">
                <div class="aui-flex-item-4">

                    <span>总成信息：</span>

                    <div style="color: white;font-size: 15px;padding-left: 1%;padding-top: 1%;">
                        <span>工单编号：</span>
                        <span id="workOrderCode"></span>
                    </div>
                    <div style="color: white;font-size: 15px;padding-left: 1%;padding-top: 1%;">
                        <span>物料编码：</span>
                        <span id="mrlCode"></span>
                    </div>

                </div>
                <div class="aui-flex-item-4">

                    <div style="color: white;font-size: 15px;padding-left: 1%;padding-top: 5%;">
                        <span>规格：</span>
                        <span id="drawing"></span>
                    </div>
                    <div style="color: white;font-size: 15px;padding-left: 1%;padding-top: 1%;">
                        <span>物料名称：</span>
                        <span id="mrlName"></span>
                    </div>
                </div>
                <div class="aui-flex-item-4">
                    <div class="startBut" style="background-color: #528302;" onclick="split()">拆分</div>
                    <div class="startBut" style="background-color: #528302;" id="submitButton" onclick="save()">提交</div>
                    <div class="startBut" style="background-color: #D9001B;" onclick="cancle()">关闭</div>

                </div>
            </div>
        </div>
        <div class="aui-flex-item-12">
            <div class="aui-flex-col line_class" style="padding-bottom: 10%;">
                <div class="aui-flex-item-12">
                    <div style="color: white;font-size: 30px;">
                        <span> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
                            - - - - - - - - - - </span>
                    </div>
                </div>
                <div class="aui-flex-item-7">
                    <div style="color: white;font-size: 15px;">
                        <span>排料信息：</span>
                    </div>
                </div>
            </div>
        </div>
        <div class="aui-flex-item-12">
            <div class="aui-flex-col pa_smbf_t">
                <div class="aui-flex-item-12">
                    <div style="height: 100%;width: 100%;">
                        <table class="table" border="1px solid gray" cellspacing="0" cellpadding="0">
                            <thead>
                                <tr style="text-align: center;color: white;font-size: 20px;">
                                    <td algin='center' style="width:3%">
                                        <!-- <input name='main' type='checkbox' id="allboxs"  onclick="allcheck()" /> -->
                                    </td>
                                    <td algin='center' style="width:5%">序号</td>
                                    <td algin='center' style="width:10%">子物料编码</td>
                                    <td algin='center' style="width:18%">规格</td>
                                    <td algin='center' style="width:12%">子物料名称</td>
                                    <td algin='center' style="width:10%">库位编码</td>
                                    <td algin='center' style="width:9%">批次号</td>
                                    <td algin='center' style="width:10%">供应商</td>
                                    <td algin='center' style="width:8%">线边库存</td>
                                    <td algin='center' style="width:10%">排料类型</td>
                                    <td algin='center' style="width:8%">报废数量</td>
                                </tr>
                            </thead>
                            <tbody id="scrapDataHtml">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<script type="text/javascript" src="../script/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="../script/public.js"></script>
<script type="text/javascript" src="../script/clickThrottle.js"></script>
<script type="text/javascript">

    var equipUniqueId = "";
    //光标所在id
    var idSelector = "";
    var arrSave = [];
    var subBussinessCode = "";
    var projectCode = ""
    var projectName = ""
    //初始化
    apiready = function () {
        //获取设备唯一号
        equipUniqueId = localStorage.getItem('equipUniqueId');
        //产线工位信息
        document.getElementById("locationName").innerHTML = api.pageParam.locationName;
        document.getElementById("workCenterName").innerHTML = api.pageParam.workCenterName;
        document.getElementById("workCellName").innerHTML = api.pageParam.workCellName;
        document.getElementById("nowDate").innerHTML = getTimeCommon();
        //当前时间刷新
        window.setInterval("getTime()", 1000);
        doSearchProductionNesting()
        //查询不合格数据
        doSearch();

        document.getElementById("workOrderCode").innerHTML = api.pageParam.workOrderCode;
        document.getElementById("mrlCode").innerHTML = api.pageParam.mrlCode;
        document.getElementById("mrlName").innerHTML = api.pageParam.mrlName;
        document.getElementById("drawing").innerHTML = api.pageParam.drawing;
    }

    //时间刷新
    function getTime() {
        document.getElementById("nowDate").innerHTML = getTimeCommon();
    }
    function doSearchProductionNesting(){
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getAssemblyProductionNesting";
        var data = {
            values: {
                un: un,
            }
        };
        var params = new Object();
        params.url = url;
        params.dataType = 'json';
        params.method = 'post';

        ajaxForData(params, data, false, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                if (myobj.code == 0) {

                    var productionNesting = eval(myobj.productionNesting);
   
                    if (productionNesting != null && productionNesting!= '') {
                        subBussinessCode = productionNesting
                        console.log(subBussinessCode)
                    }else{
                        subBussinessCode = '3710'
                    }

                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                alert("网络连接超时!")
            }

        });
    }
    //查询子物料在线边库库存
    function doSearch() {
        arrSave = [];
        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/getAssemblyScrapDetailZS";
        var data = {
            values: {
                workOrderCode: api.pageParam.workOrderCode,
                workCenterCode: api.pageParam.workCenterCode,
                un: un,
            }
        };
        var params = new Object();
        params.url = url;
        params.dataType = 'json';
        params.method = 'post';

        ajaxForData(params, data, false, function (ret, err) {
            if (ret) {
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");

                //成功
                if (myobj.code == 0) {

                    var list = eval(myobj.list);
                    if (list) {
                        for (var i = 0; i < list.length; i++) {
                            var model = {
                                mrl_code: list[i].mrl_code,
                                drawing: list[i].drawing,
                                qty: list[i].qty,
                                mrl_name: list[i].mrl_name,
                                work_cell_code: list[i].work_cell_code,
                                lot_code: list[i].lot_code,
                                ext03: list[i].ext03,
                                causeOfDeficiency: "",
                                qxTypeCode: "",
                                chkItemTypeId: "",
                                scrapQty: 0
                            }
                            arrSave.push(model);
                        }
                        setTable(arrSave);
                    }


                } else {
                    $api.html($api.byId("scrapDataHtml"), "");
                    api.toast({
                        msg: myobj.message,
                        duration: 3000
                    });
                }
            } else {
                alert("网络连接超时!")
            }
        });
    }

    function setTable(list) {
        var html = "";
        var causeOfDeficiency = ""
        var scrapQty = ""
        //遍历
        for (var i = 0; i < list.length; i++) {
            causeOfDeficiency = "causeOfDeficiency_" + i
            scrapQty = "scrapQty_" + i
            html += "<tr style='text-align: center;color: white;font-size: 14px;height:50px;'>";
            html += "<td><input name='sub' type='checkbox' /></td>"
            html += "<td name='index'>" + (i + 1) + "</td>";
            html += "<td name='mrl_code'>" + list[i].mrl_code + "</td>";
            html += "<td><div class='marquee' name='drawing' id='drawing'>" + list[i].drawing + "</div></td>";
            html += "<td><div class='marquee' name='mrl_name' id='mrl_name'>" + list[i].mrl_name + "</div></td>";
            html += "<td name='work_cell_code'>" + list[i].work_cell_code + "</td>";
            html += "<td name='lot_code'>" + list[i].lot_code + "</td>";
            html += "<td name='ext03'>" + list[i].ext03 + "</td>";
            html += "<td name='qty'>" + list[i].qty + "</td>";
            html += "<td name='causeOfDeficiency' width = '19%'><input type='search' readOnly ='true' id=\"" + causeOfDeficiency + "\"  onclick='opencauseOfDeficiency(\"" + causeOfDeficiency + "\" );' style='color:black;background-color:white; height:30px; min-height:50px;' value=\"" + list[i].causeOfDeficiency + "\" /></td>";
            html += "<td  name='scrapQty' width = '19%'><input type='number' id=\"" + scrapQty + "\"  onblur='changeScrapQty(\"" + scrapQty + "\",\"" + list[i].scrapQty + "\",\"" + list[i].qty + "\" );' style='color:black;background-color:white; height:30px; min-height:50px;' value=\"" + list[i].scrapQty + "\" /></td>";

            html += "<td name='scrapQty'>" + "" + "</td>";
            html += "</tr>";
        }

        $api.html($api.byId("scrapDataHtml"), html);
        // 获取td中的div元素
        var tdElements = document.querySelectorAll('td div');

        // 遍历div元素
        for (var i = 0; i < tdElements.length; i++) {
            // 获取当前ddiv元素的宽度
            var tdWidth = tdElements[i].offsetWidth;

            // 获取当前div元素中输入的内容长度
            var contentLength = tdElements[i].scrollWidth;

            // 判断内容长度是否大于div的宽度
            if (contentLength > tdWidth) {

            } else {
                //移除跑马灯效果
                tdElements[i].classList.remove("marquee");
            }
        }
    }
    function changeScrapQty(scrapQtyId, scrapQty, stockQty) {
        var qty = document.getElementById(scrapQtyId).value;
        if (parseInt(qty) < 0) {
            api.toast({
                msg: '不能是负数！',
                duration: 3000
            });
            for (var i = 0; i < arrSave.length; i++) {
                if ("scrapQty_" + i == scrapQtyId) {
                    arrSave[i].scrapQty = scrapQty
                }
            }

            setTable(arrSave);

        } else if (Number(qty) > Number(stockQty)) {
            api.toast({
                msg: '报废数量不能大于库存数！',
                duration: 3000
            });
            for (var i = 0; i < arrSave.length; i++) {
                if ("scrapQty_" + i == scrapQtyId) {
                    arrSave[i].scrapQty = scrapQty
                }
            }

            setTable(arrSave);
        } else {
            for (var i = 0; i < arrSave.length; i++) {
                if ("scrapQty_" + i == scrapQtyId) {
                    arrSave[i].scrapQty = qty
                }
            }

            setTable(arrSave);
        }

    }


    function opencauseOfDeficiency(causeOfDeficiency) {
        var pageParam = api.pageParam;
        pageParam.name = "productionAssemblyScrap_detail";
        pageParam.causeOfDeficiency = causeOfDeficiency;
        api.openWin({
            name: "causeOfDeficiency",
            url: 'causeOfDeficiency.html',
            pageParam: pageParam,
        });
    }

    function setScrapName(flawCode, flawName, causeOfDeficiency, chkItemTypeId) {
        for (var i = 0; i < arrSave.length; i++) {
            document.getElementById("causeOfDeficiency_" + i).innerHTML = flawName;
            if ("causeOfDeficiency_" + i == causeOfDeficiency) {
                arrSave[i].causeOfDeficiency = flawName
                arrSave[i].qxTypeCode = flawCode
                arrSave[i].chkItemTypeId = chkItemTypeId
            }
        }
        setTable(arrSave);

    }

    //拆分
    function split() {
        //选中数据
        var check = $("input[type='checkbox']:checked"); //在table中找input下类型为checkbox属性为选中状态的数据
        var count = 0;
        var mrl_code = "";
        var drawing = "";
        var qty = 0;
        var mrl_name = "";
        var work_cell_code = "";
        var lot_code = "";
        var ext03 = "";
        var causeOfDeficiency = "";
        var scrapQty = 0;
        check.each(function () { //遍历
            var row = $(this).parent("td").parent("tr");
            mrl_code = row.find("[name='mrl_code']").html();
            drawing = row.find("[name='drawing']").html();
            qty = row.find("[name='qty']").html();
            mrl_name = row.find("[name='mrl_name']").html();
            work_cell_code = row.find("[name='work_cell_code']").html();
            lot_code = row.find("[name='lot_code']").html();
            ext03 = row.find("[name='ext03']").html();
            count++;
        });
        if (count != 1) {
            api.toast({
                msg: '请选择一条表格数据！',
                duration: 3000
            });
            return;
        }
        var model = {
            mrl_code: mrl_code,
            drawing: drawing,
            qty: qty,
            mrl_name: mrl_name,
            work_cell_code: work_cell_code,
            lot_code: lot_code,
            ext03: ext03,
            causeOfDeficiency: "",
            qxTypeCode: "",
            chkItemTypeId: "",
            scrapQty: 0
        }
        arrSave.push(model);
        setTable(arrSave);
    }

    //提交
    function save() {

        if (!clickThrottle()) {
            return;
        }
        var list = [];
        //选中数据
        var check = $("input[type='checkbox']:checked"); //在table中找input下类型为checkbox属性为选中状态的数据
        var count = 0;
        var scrapQty = 0;
        var index = 0;
        var causeOfDeficiency = "";
        var flag = false;
        check.each(function () { //遍历
            var row = $(this).parent("td").parent("tr");
            index = row.find("[name='index']").html();
            var ss = index - 1;
            if (Number(ss) >= 0) {
                scrapQty = arrSave[ss].scrapQty;
                causeOfDeficiency = arrSave[ss].causeOfDeficiency;
                if (Number(scrapQty) == 0) {
                    api.toast({
                        msg: '报废数量应该大于0！',
                        duration: 3000
                    });
                    flag = true;

                    return;
                }
                if (causeOfDeficiency == "") {
                    api.toast({
                        msg: '报废原因不能为空！',
                        duration: 3000
                    });
                    flag = true;
                    return;
                }
                list.push(arrSave[ss]);
            }

            count++;

        });
        if (flag) {
            return;
        }
        if (count == 0) {
            api.toast({
                msg: '请至少选择一条表格数据！',
                duration: 3000
            });
            return;
        }
        var summary = {};

        list.reduce(function (acc, cur) {
            var key = cur.mrl_code + '-' + cur.work_cell_code + '-' + cur.lot_code + '-' + cur.ext03;
            if (summary[key]) {
                summary[key].scrapQty = Number(summary[key].scrapQty) + Number(cur.scrapQty);
            } else {
                // 否则，创建一个新的条目
                summary[key] = {
                    mrl_code: cur.mrl_code,
                    drawing: cur.drawing,
                    qty: cur.qty,
                    mrl_name: cur.mrl_name,
                    work_cell_code: cur.work_cell_code,
                    lot_code: cur.lot_code,
                    ext03: cur.ext03,
                    causeOfDeficiency: cur.causeOfDeficiency,
                    qxTypeCode: "",
                    chkItemTypeId: "",
                    scrapQty: cur.scrapQty,
                };
            }
        }, {});

        // 最后，将汇总结果转换为数组
        var listNew = Object.values(summary);
        console.log(JSON.stringify(list))
        console.log(JSON.stringify(listNew))
        for(var i = 0;i < listNew.length;i++){
            if(listNew[i].scrapQty > listNew[i].qty){
                api.toast({
                    msg: '报废数量不允许大于线边库存数！',
                    duration: 3000
                });
                return;
            }
        }


        const submitButton = document.getElementById('submitButton');
        submitButton.style.pointerEvents = "none"; // 禁用提交按钮

        var un = localStorage.getItem('un');
        var serverUrl = localStorage.getItem('serverUrl');
        var url = serverUrl + "/app/saveScrapByWorkOrder";
        var data = {
            values: {
                workOrderCode: api.pageParam.workOrderCode,
                projectCode: projectCode,
                subBussinessCode: subBussinessCode,
                list: JSON.stringify(list),
                un: un
            }
        };

        var params = new Object();
        params.url = url;
        params.dataType = 'json';
        params.method = 'post';

        api.showProgress({
            title: '保存中...',
        });

        ajaxForData(params, data, false, function (ret, err) {
            if (ret) {
                submitButton.style.pointerEvents = "auto"; // 启用提交按钮
                api.hideProgress();
                var data = JSON.stringify(ret);
                var myobj = eval("(" + data + ")");
                //成功
                if (myobj.code == 0) {
                    api.toast({
                        msg: "保存成功!",
                        duration: 3000
                    });
                    arrSave = [];
                    //查询表格数据
                    doSearch();

                } else {
                    api.toast({
                        msg: myobj.message,
                        duration: 8000
                    });
                    arrSave = [];
                    //查询表格数据
                    doSearch();
                }
            } else {
                submitButton.style.pointerEvents = "auto"; // 启用提交按钮
                api.hideProgress();
                alert("网络连接超时!")
            }
        });
    }

    //刷新按钮
    function refresh() {

        //获取设备唯一号
        equipUniqueId = localStorage.getItem('equipUniqueId');
        doSearchProductionNesting()
        //查询表格数据
        doSearch();

    }

    //取消,返回上一级
    function cancle() {
        api.closeWin({});
        api.execScript({
            name: api.pageParam.name,
            script: 'refresh()'
        });
    }

    //返回按钮
    function closeWin() {
        api.closeToWin({ name: api.pageParam.rootName });
        api.execScript({
            name: api.pageParam.rootName,
            script: 'refresh()'
        });
    }
</script>

</html>